package com.lsy.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.lsy.entity.FlowRecordType;
import com.lsy.entity.Flowrecord;
import com.lsy.entity.Interest;
import com.lsy.entity.Invest;
import com.lsy.entity.ProductCustom;
import com.lsy.mapper.interf.InterestMapper;
import com.lsy.mapper.interf.InvestMapper;
import com.lsy.mapper.interf.ProductMapperCustom;
import com.lsy.service.interf.FlowRecordService;
import com.lsy.service.interf.InterestService;
import com.lsy.service.interf.UserService;
import com.lsy.util.DateUtil;

@Service
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class InterestServiceImpl implements InterestService {

	/**
	 * 定时任务每次处理数目
	 */
	private final int NUMBER = 50;

	private final int EXPIRE = 1;
	private final int MONTH_INTEREST = 2;
	private final int MONTH_PRINCIPAL_INTEREST = 3;

	@Autowired
	private ProductMapperCustom productMapper;

	@Autowired
	private InterestMapper interestMapper;

	@Autowired
	private InvestMapper investMapper;

	@Autowired
	private FlowRecordService flowRecordService;

	@Autowired
	private UserService userService;

	public boolean save(Interest object) throws RuntimeException {
		boolean result = false;
		if (interestMapper.insert(object) > 0) {
			result = true;
		}
		return result;
	}
	
	//定时任务  检查是否需要发放利息
	@Scheduled(cron = "0 0 0 * * ?")
	public void productInterest() throws Exception {
		int total = productMapper.findIsDoneTotal();
		int page = total % NUMBER == 0 ? total / NUMBER : total / NUMBER + 1;
		for (int i = 0; i < page; i++) {
			int from = i * NUMBER;
			List<ProductCustom> products = productMapper.findIsDoneProductByPage(from, NUMBER);
			for (ProductCustom product : products) {
				Calendar calendar = DateUtil.getNumberNext(product.getPdonetime(), product.getPtimelimit());
				switch (product.getPtype()) {
				case EXPIRE:
					if (DateUtil.isToday(calendar)) {
						System.out.println("返利开始！");
						sureReceive(product.getProductid());
					}
					break;
				default:
					int interval = DateUtil.getIntervalFromNow(calendar);
					if (interval >= 0) {
						int day = calendar.get(Calendar.DAY_OF_MONTH);
						if ((DateUtil.isLastDayOfMonth() && DateUtil.getDay() < day) || day == DateUtil.getDay()) {
							sureReceive(product.getProductid());
							if (interval > 0) {
								createInterestByProduct(product);
							}
						}
					}
					break;
				}
			}
		}
	}
	// 创建利息信息
	public int createInterestByProduct(ProductCustom product) throws Exception {

		List<Invest> invests = investMapper.findInvestByProductId(product.getProductid());
		Date currentTime = null;
		float currentInterest = 0;
		Interest interest = null;
		int number = 0;
		switch (product.getPtype()) {
		case EXPIRE:  //散标类型一：到期返还本金利息
			currentTime = DateUtil.getNumberNext(product.getPdonetime(), product.getPtimelimit()).getTime();
			for (Invest invest : invests) {
				//计算利息
				currentInterest = (float) (invest.getIlendmoney() * product.getPrate()* 0.01 * product.getPtimelimit()/12);
				//新建利息记录
				interest = new Interest();
				interest.setIinterestcurrent((int)currentInterest);
				interest.setImoneycurrent(invest.getIlendmoney());
				interest.setImandicurrent(interest.getIinterestcurrent() + interest.getImoneycurrent());
				interest.setInvestid(invest.getInvestid());
				interest.setIpaidback(false);
				interest.setItimecurrent(currentTime);
				save(interest);
				number++;
			}
			break;
		case MONTH_INTEREST:
			Calendar nextMonth = DateUtil.getNumberNext(product.getPdonetime(), 1);
			Calendar finalDate = DateUtil.getNumberNext(product.getPdonetime(), product.getPtimelimit());
			currentTime = nextMonth.getTime();
			for (Invest invest : invests) {
				currentInterest = (float) (invest.getIlendmoney() * product.getPrate()*0.01*(1/12));
				interest = new Interest();
				interest.setIinterestcurrent((int)currentInterest);
				if (DateUtil.isSameMonth(nextMonth, finalDate)) {
					interest.setImoneycurrent(invest.getIlendmoney());
				}
				interest.setImandicurrent(interest.getIinterestcurrent() + interest.getImoneycurrent());
				interest.setInvestid(invest.getInvestid());
				interest.setIpaidback(false);
				interest.setItimecurrent(currentTime);
				save(interest);
				number++;
			}
			break;
		case MONTH_PRINCIPAL_INTEREST:
			Calendar calendar = DateUtil.getNumberNext(product.getPdonetime(), product.getPtimelimit());
			int interval = DateUtil.getIntervalFromNow(calendar);
			currentTime = DateUtil.getNumberNext(product.getPdonetime(), 1).getTime();
			// 本次本金
			int cash = 0;
			for (Invest invest : invests) {
				if (interval == 1) {
					cash = invest.getIlendmoney();
				} else {
					cash = invest.getIlendmoney() / interval;
				}
				currentInterest = (float) (invest.getIlendmoney() * product.getPrate()*0.01*(1/12));
				interest = new Interest();
				interest.setIinterestcurrent((int)currentInterest);
				interest.setImoneycurrent(cash);
				interest.setImandicurrent(interest.getIinterestcurrent() + interest.getImoneycurrent());
				interest.setInvestid(invest.getInvestid());
				interest.setIpaidback(false);
				interest.setItimecurrent(currentTime);
				save(interest);
				invest.setIlendmoney(invest.getIlendmoney() - cash);
				investMapper.updateByPrimaryKey(invest);
				number++;
			}
			break;
		default:
			break;
		}
		return number;
	}
	//收到返还利息
	public int sureReceive(int productId) throws Exception {
		List<Invest> invests = investMapper.findInvestByProductId(productId);
		int number = 0;
		Flowrecord record = null;
		for (Invest invest : invests) {
			if (interestMapper.sureReciveByInvestId(invest.getInvestid()) > 0) {
				// 生成流水账单
				int currentInterest = interestMapper.findNewestInterestByInvestId(invest.getInvestid());
				record = new Flowrecord();
				record.setProductid(productId);
				record.setFmoneyleft((int) (userService.findUserMoney(invest.getUserid())));
				record.setFtimedeal(new Date());
				record.setFtypedeal(FlowRecordType.BACK_CASH.getType());
				record.setUserid(invest.getUserid());
				record.setFmoneydeal(currentInterest);
				flowRecordService.save(record);
				number++;
			}
		}
		return number;
	}

	public List<Interest> findList() throws Exception {
		// TODO Auto-generated method stub
		return interestMapper.findList();
	}

}
